/*
    storage 主要放项目中的storage相关操作：存取等
*/
const storage = {
  hasLocalSotrage: function () {
    return window.Storage && window.localStorage && window.localStorage instanceof Storage
  },
  /**
   对本地数据进行操作的相关方法，如localStorage,sessionStorage的封装
   */
  setStorage: function (key, value, days) {
    const Days = days || 1 // 默认保留1天
    const exp = new Date()
    let data = {
      value: value,
      expiryTime: exp.getTime() + Days * 24 * 60 * 60 * 1000
    }
    localStorage[key] = JSON.stringify(data)
  },
  getStorage: function (key) {
    const data = localStorage[key]
    if (!data || data === 'null') {
      return null
    }
    const now = this.getCurrentTimeStamp()
    let obj
    try {
      obj = JSON.parse(data)
    } catch (e) {
      return null
    }
    if (obj.expiryTime === 0 || obj.expiryTime > now) {
      return obj.value
    }
    return null
  },
  removeStorage: function (key) {
    localStorage.removeItem(key)
  },
  clearStorage: function () {
    localStorage.clear()
  },
  getSession: function (key) {
    const data = sessionStorage[key]
    if (!data || data === 'null') {
      return null
    }
    return JSON.parse(data).value
  },
  setSession: function (key, value) {
    let data = {
      value: value
    }
    sessionStorage[key] = JSON.stringify(data)
  },
  removeSession: function (key) {
    sessionStorage.removeItem(key)
  },
  getCurrentTimeStamp: function () {
    return Date.parse(new Date())
  }
}
export default storage
